package com.beyond.pm.local

import android.widget.Toast
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.mutableStateOf
import androidx.navigation.NavDestination
import androidx.navigation.NavHostController
import com.beyond.common.constant.LOGIN_ROUTE
import com.beyond.common.constant.routes
import com.beyond.common.manager.UserManager
import com.beyond.pm.dp.LanguagePreference

// 定义全局的load状态
val loadStatusState = mutableStateOf(false)
val snackStatusState = mutableStateOf(SnackbarHostState())

// 语言
val LocalLanguageState = compositionLocalOf { LanguagePreference.default }

// val nav = AppNavController.current
// val appNav = remember(AppNavController.current) { AppNavHostController(nav) }
val LocalNavController = compositionLocalOf<NavHostController> {
    error("AppNavController not initialized!")
}

class AppNavHostController(private val navController: NavHostController) {
    fun navigate(route: String) {
        if (routes.contains(route)) {
            // 在这里进行路由拦截
            if (isLoggedIn()) {
                // 如果用户未登录，则跳转到登录页
                navController.navigate(LOGIN_ROUTE)
            } else {
                // 先判断路由页面是否存在  否则正常导航到目标页
                val destination = navController.graph.findNode(route)
                if (destination is NavDestination && navController.currentDestination?.id != destination.id) {
                    navController.navigate(destination.id)
                } else {
                    Toast.makeText(navController.context, "$route 没有找到", Toast.LENGTH_LONG)
                        .show()
                }
            }
        } else {
            Toast.makeText(navController.context, "$route 没有注册", Toast.LENGTH_LONG).show()
        }
    }

    fun popBackStack() {
        navController.popBackStack()
    }

    private fun isLoggedIn(): Boolean {
        // 判断用户是否已登录  true 为 未登录
        return UserManager.user?.token.isNullOrEmpty()
    }
}

